<?php
/**
 * Created by PhpStorm.
 * User: zhaoyi
 * Date: 2022/1/26
 * Time: 11:46.
 */

declare(strict_types=1);

namespace App\Application\Api\Controller;

use App\Annotation\Api;
use App\Application\Admin\Model\Coupon;
use App\Application\Admin\Model\Meituan;
use App\Application\Admin\Model\Room;
use App\Application\Admin\Model\Tiktok;
use App\Application\Admin\Service\AdminSettingService;
use App\Application\Admin\Service\CityService;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Controller;

#[Controller("/api/tiktok/")]
class TiktokController extends AbstractController
{
    #[Inject]
    protected AdminSettingService $setting;
    /*
     *
     *核销
     * */
    #[Api]
    #[PostMapping("index")]
    function index()
    {
        $user = $this->checkToken();
        $receipt_code = trim($this->request->input('receipt_code', ''));
        $store_id = trim($this->request->input('store_id', ''));
        // 查询门店
        $store = Tiktok::where('store_id', $store_id)->select('*')
            ->first() ?: [];
        if (empty($store)) {
            return $this->returnErrorJson('当前门店未配置抖音验券信息,请切换门店后验券');
        }
        if ($store->expire_in < time()) {
            $data['client_key'] = $store->client_key;
            $data['client_secret'] = $store->client_secret;
            $data['grant_type'] = "client_credential";
            $header = array(
                'Content-Type:' . 'multipart/form-data'
            );
            $url = "https://open.douyin.com/oauth/client_token/";
            $res = self::curl_postdy($url, $data, $header);
            $return = json_decode($res, true);
            if ($return['message'] == "success") {
                $da['access_token'] = $return['data']['access_token'];
                $da['expires_in'] = time() + 7000;
                Tiktok::where('tiktok_id', $store->tiktok_id)->update($da);
                $store->access_token = $return['data']['access_token'];
            }
        }

        if ($store->access_token) {
            $header = array(
                'Content-Type:' . 'application/json',
                'access-token:' . $store->access_token
            );
            if (preg_match("/^(http:\/\/|https:\/\/).*$/", $receipt_code)) {
                $encrypted_data = self::douyin($receipt_code);
                $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $encrypted_data;
            } else {
                $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $receipt_code;
            }
            $res = self::curl_get($url, $header);
            $return = json_decode($res, true);
            if (isset($return['data']['certificates']) || 1) {
                if (isset($return['data']['certificates']) || 1) {
                    $goods_id = $return['data']['certificates'][0]['sku']['sku_id'];
                    if ($goods_id) {
                        $card_where['trill_id'] = $goods_id;
                        $card_list = Coupon::where($card_where)->select('*')
                            ->first() ?: [];;
                    }
                    // 查询对应的兑换
                    if (empty($card_list)) {
                        return $this->returnErrorJson('暂无兑换的优惠卡,请稍后再试');
                    }
                    $encrypted_code = $return['data']['certificates'][0]['encrypted_code'];
                    $verify_token = $return['data']['verify_token'];
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/verify/";
                    $ya['verify_token'] = $verify_token;
                    $ya['poi_id'] = $store->poi_id;
                    $ya['encrypted_codes'][] = $encrypted_code;
                    $res = self::curl_postdy($url, json_encode($ya), $header);
                    $return = json_decode($res, true);
                    if (!isset($return['data'])) {
                        return $this->returnErrorJson('此券已核销');
                    }
                    if ($return['data']['error_code'] == 0) {
                        if ($return['data']['verify_results'][0]['result'] != 0) {
                            return $this->returnErrorJson($return['data']['verify_results'][0]['msg']);
                        }
                        $card_list = Coupon::where($card_where)->select('*')
                            ->first() ?: [];;
                        $dataCoupon = array(
                            'coupon_id' => $card_list->coupon_id,
                            'name' => $card_list->name,
                            'condition' => $card_list->condition,
                            'roomids' => json_encode($card_list->roomids),
                            'time' => $card_list->time,
                            'hours_add_time' => $card_list->hours_add_time,
                            'hours_end_time' => $card_list->hours_end_time,
                            'member_id' => $user->member_id,
                            'store_id' => $store_id,
                            'type' => $card_list->type,
                            'money' => $card_list->money,
                            'price' => $card_list->price,
                            'end_time' => $card_list->end_time,
                        );

                        if (Db::table('coupon_member')->insert($dataCoupon)) {
                            // 更新领取数量
                            $coi = array(
                                'num' => $card_list['num'] - 1,
                            );
                            $rescoupon = Coupon::where('coupon_id', $card_list->coupon_id)->update($coi);
                            return $this->returnSuccessJson(compact('rescoupon'));
                        }

                    } else {
                        return $this->returnErrorJson($return['data']['description']);
                    }
                } else {
                    return $this->returnErrorJson('此券已核销');
                }
            } else {
                return $this->returnErrorJson($return['data']['description']);
            }
        } else {
            return $this->returnErrorJson('获取access_token配置信息失败');
        }
    }
}